<template>
    <view class="uni-padding-wrap uni-common-mt">

        <div class="chat-room">
            <div class="messages">
                <div v-for="message in messages" :key="message.id"
                    :class="['message', { 'self': message.userId === userId }]">
                    <span class="user">{{ message.userId }}</span>
                    <span class="text">{{ message.content }}</span>
                </div>
            </div>



            <div class="input-area">
                <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message..." />
                <button @click="sendMessage">Send</button>
            </div>



            <uni-row :gutter="2" style="margin-bottom: 10px;">
                <uni-col :span="6">
                    <view class="">
                        <button type="default" class="backgroundStyle">
                            <uni-icons type="image" size="30"></uni-icons>
                        </button>
                    </view>
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="camera-filled" size="30"></uni-icons>
                        </button></view>
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="phone-filled" size="30"></uni-icons>
                        </button></view>
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="location-filled" size="30"></uni-icons>
                        </button></view>
                </uni-col>
            </uni-row>


            <uni-row :gutter="2">
                <uni-col :span="6">

                    <view>



<view class="upload-img">
	<uni-file-picker limit="6" 
					@select='selectUpload' 
					:auto-upload='false' 
					file-mediatype="all" 
					:list-styles='listStyles' 
					v-model='fileList'
		>
		<button>点击上传</button>
	</uni-file-picker>

</view>







                        <!-- 文件选择器 -->
                        <!-- <uni-file-picker ref="filePicker" :count="1" 
                            @change="onFileChange">
                            <button type="primary">选择文件</button>
                        </uni-file-picker> -->

                        <!-- 上传按钮（可选，也可以在选择文件后自动上传） -->
                        <!-- <button type="primary" @click="uploadFile">上传文件</button> -->
                    </view>



                    <!-- <view class=""> 
                        <button type="default">

                        <uni-icons custom-prefix="iconfont" type="icon-file" size="30"></uni-icons>

                        </button>
                    </view> -->
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="contact" size="30"></uni-icons>
                        </button></view>
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="mic-filled" size="30"></uni-icons>
                        </button></view>
                </uni-col>
                <uni-col :span="6">
                    <view class=""> <button type="default">
                            <uni-icons type="contact" size="30"></uni-icons>
                        </button></view>
                </uni-col>
            </uni-row>







        </div>


    </view>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import WebSocketClient from '../../utils/websocket-client';
// import { plus, uni } from '@dcloudio/uni-app'; // 确保已经正确引入了 uni-app 的相关模块

export default {
    name: 'chatRoom',
    setup() {
        const userId = '350';   // temp value for test
        const groupId = '22';    // temp value for test
        const messages = reactive([]);
        const newMessage = ref('');
        const filePath = ref(''); // 存储选中的文件路径
        const sendId = ref('350'); // 可选参数，根据需求设置
        const fileList=[];
        const listStyles= {
			"borderStyle": {
				"width": "0", // 边框宽度
			},
			"border": false, // 是否显示边框
			"dividline": false
		}


        let socketClient;

        const addMessage = (message) => {
            messages.push({
                id: Date.now(),
                userId: message.userId,
                groupId: message.groupId,
                content: message.content
            });
        };

        const onWebSocketMessage = (data) => {
            const { userId: msgUserId, content, groupId: msgGroupId } = data;
            if (msgGroupId === groupId) {
                addMessage({ userId: msgUserId, content });
            }
        };

        const connectWebSocket = () => {
            socketClient = new WebSocketClient(userId, groupId, onWebSocketMessage);
        };

        const sendMessage = () => {
            if (newMessage.value.trim()) {
                socketClient.sendMessage({ content: newMessage.value });
                newMessage.value = '';
            }
        };

        const selectUpload = (e) => {
            // 假设 e.file.path 是文件路径，e.file.name 是原文件名
            // const filePath = e.file ? e.file.path : '';
            // const fileName = e.file ? e.file.name : ''; // 获取原文件名
            // filePath.value = filePath;
            // // 可选：在 formData 中发送文件名（如果后端支持保留原文件名）
            // const originalFileName = ref(fileName);

            // // 选择文件后自动上传
            // uploadFile(originalFileName.value); // 如果后端不需要原文件名，这里可以不传或省略

            uni.uploadFile({
		url: 'http://127.0.0.1:8080/wechat/client/upload', //仅为示例，非真实的接口地址
		filePath: e.tempFilePaths[0],
		name: 'file',
		// formData: {
		// 	'file': ''
		// },
		success: (uploadFileRes) => {
			console.log(uploadFileRes.data);
		},
		fail: (err) => {
			console.log(err);
		}
	})


        };

        const uploadFile = (originalFileName = '') => {
            if (!filePath.value) {
                uni.showToast({
                    title: '请先选择文件2',
                    icon: 'none',
                });
                return;
            }

            console.log("---------------------");
          console.log("filePath.value:"+filePath.value);
          console.log("e.tempFilePaths[0]:"+e.tempFilePaths[0]);


            uni.uploadFile({
		url: 'http://127.0.0.1:8080/wechat/client/upload', //仅为示例，非真实的接口地址
		filePath: e.tempFilePaths[0],
		name: 'file',
		// formData: {
		// 	'file': ''
		// },
		success: (uploadFileRes) => {
			console.log(uploadFileRes.data);
		},
		fail: (err) => {
			console.log(err);
		}
	})


            // uni.uploadFile({
            //     url: 'http://127.0.0.1:8080/wechat/client/upload', // 上传接口
            //     filePath: filePath.value,
            //     name: 'file', // 后台接收的文件参数名需与后端接口对应
            //     formData: {
            //         sendId: sendId.value, // 可选参数
            //         groupId: groupId, // 可选参数
            //         // 如果后端支持，可以发送原文件名
            //         // originalFileName: originalFileName, // 注释掉或启用，根据后端需求
            //     },
            //     success: (uploadFileRes) => {
            //         // 上传成功后的回调
            //         const data = JSON.parse(uploadFileRes.data);
            //         // 处理返回的数据，比如显示上传结果等
            //         console.log('上传成功', data);
            //     },
            //     fail: (err) => {
            //         // 上传失败后的回调
            //         console.error('上传失败', err);
            //         uni.showToast({
            //             title: '上传失败',
            //             icon: 'none',
            //         });
            //     },
            // });
        };


        // const uploadSuccess=(res)=> {
        //     console.log('uploadSuccess', res);
        // };
        
        // const uploadFail=(err)=> {
        //     console.log('uploadFail', err);
        // };


        onMounted(() => {
            connectWebSocket();
        });

        onUnmounted(() => {
            if (socketClient) {
                socketClient.close(); // 确保 WebSocket 连接在组件卸载时被关闭
            }
        });

        return {
            userId,
            groupId,
            messages,
            newMessage,
            filePath,
            sendId,
            sendMessage,
            selectUpload,
            uploadFile,
            fileList,
            listStyles

        };
    }
};
</script>

<style scoped>
.chat-room {
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    border: 1px solid #ccc;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 0 30rpx;

}

.messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
}

.message {
    display: flex;
    margin-bottom: 10px;
}

.message.self {
    justify-content: flex-end;
    background-color: #dcf8c6;
}

.message:not(.self) {
    justify-content: flex-start;
    background-color: #e0f7fa;
}

.user {
    font-weight: bold;
    margin-right: 5px;
}

.text {
    padding: 5px 10px;
    border-radius: 5px;
}

.input-area {
    display: flex;
    padding: 10px;
    background-color: #f9f9f9;
    border-top: 1px solid #ccc;
}

input {
    flex: 1;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    margin-left: 10px;
    padding: 5px 10px;
    border: none;
    background-color: #ddd;
    color: white;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
</style>